import { Close } from '@mui/icons-material';
import {
    Alert,
    Box,
    Button,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    IconButton
} from '@mui/material';
import create from 'zustand';

import { useStyles } from './UIs/styled-mui-dialog';

type ConfirmDialogStore = {
    title: string;
    message: string | JSX.Element;
    onSubmit?: () => void;
    close: () => void;
};

type ConfirmDialogFnc = {
    title?: string;
    message: string | JSX.Element;
    onSubmit?: () => void;
};

const useConfirmDialogStore = create<ConfirmDialogStore>((set) => ({
    title: '',
    message: '',
    onSubmit: undefined,
    close: () => set({ onSubmit: undefined })
}));

export const confirmDialog = ({
    title = 'Confirm the action',
    message,
    onSubmit
}: ConfirmDialogFnc) => {
    useConfirmDialogStore.setState({
        title,
        message,
        onSubmit
    });
};

const ConfirmDialog = () => {
    const c = useStyles();
    const { message, onSubmit, close, title } = useConfirmDialogStore();
    return (
        <Dialog open={!!onSubmit} onClose={close} maxWidth="sm" fullWidth>
            <Box display="flex" justifyContent="space-between" alignItems="center">
                <DialogTitle>{title}</DialogTitle>
                <IconButton onClick={close}>
                    <Close />
                </IconButton>
            </Box>
            <DialogContent>
                <Alert severity="warning">{message}</Alert>
            </DialogContent>
            <DialogActions className={c.props}>
                <Button color="primary" variant="contained" onClick={close}>
                    Cancel
                </Button>
                <Button
                    color="secondary"
                    variant="contained"
                    onClick={() => {
                        if (onSubmit) {
                            onSubmit();
                        }
                        close();
                    }}
                >
                    Process
                </Button>
            </DialogActions>
        </Dialog>
    );
};

export default ConfirmDialog;
